<template>
  <div class="p-2">

    <el-tabs v-loading="loading"  v-model="activeName" class="demo-tabs" style="margin-left: 25px;">
      <!-- 页签 -->
      <el-tab-pane v-for="(tab, tabIndex) in tabList" :label="tab.tabName" :name="tab.tabName">
        <div v-for="formInfo in formInfoList">
          <div v-if="tab.formIdList.includes(formInfo.formId)">
            <!-- 表单 -->
            <h3>{{formInfo.formName}}</h3>
            <el-divider />
            <!-- 表单分组 -->
<!--            <div v-for="formId in tab.formIdList">-->
              <div v-if="formInfo.showType == 1">
                <el-form label-width="120px" v-model="formData.formId" :key="formInfo.formId">
                  <div v-for="(data,index) in formData.get(formInfo.formId)">
                    表单{{index+1}}
                    <div v-for="group in formInfo.groupList">
                      <h4>{{ group.groupName}}</h4>
                      <div v-for="item in group.formFieldList">
                        <el-form-item v-if="item.isHidden == 'N'" :label="item.chineseName" :prop="item.fieldName" :key="item.sheetFieldId">
                          <el-input v-if="item.showType==1" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"/>
                          <el-input-number v-if="item.showType==2" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"/>
                          <el-input-number v-if="item.showType==3" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" :precision="2" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"/>
                          <el-input v-if="item.showType==4" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]" type="textarea"/>
                          <editor v-if="item.showType==5"  :min-height="192" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"/>
                          <el-select v-if="item.showType==6" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"
                                     :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, index)"
                                     clearable filterable>
                            <el-option
                              v-for="data in item.sourceList"
                              :key="data.value"
                              :label="data.label"
                              :value="data.value"
                            ></el-option>
                          </el-select>
                          <el-select v-if="item.showType==7" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"
                                     :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, index)"
                                     multiple clearable filterable>
                            <el-option
                              v-for="data in item.sourceList"
                              :key="data.value"
                              :label="data.label"
                              :value="data.value"
                            ></el-option>
                          </el-select>
                          <el-cascader v-if="item.showType==8" :disabled="item.isEdit=='N'" :options="item.sourceList"
                                       :placeholder="item.fieldTip"
                                       v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"
                                       :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, index)"
                                       clearable filterable/>
                          <el-cascader v-if="item.showType==9" :disabled="item.isEdit=='N'" :options="item.sourceList"
                                       :props="{ multiple: true }"
                                       :placeholder="item.fieldTip"
                                       v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"
                                       :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, index)"
                                       clearable filterable/>
                          <el-tree-select v-if="item.showType==10" :disabled="item.isEdit=='N'" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"
                                          :placeholder="item.fieldTip"
                                          :data="item.sourceList"
                                          :render-after-expand="false"
                                          :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, index)"
                                          clearable filterable show-checkbox
                          />
                          <el-tree-select v-if="item.showType==11" :disabled="item.isEdit=='N'" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"
                                          :placeholder="item.fieldTip"
                                          :data="item.sourceList"
                                          :render-after-expand="false"
                                          :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, index)"
                                          show-checkbox multiple clearable filterable
                          />
                          <el-date-picker v-if="item.showType==12" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]" type="year" value-format="YYYY" />
                          <el-date-picker v-if="item.showType==13" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]" type="month" value-format="YYYY-MM"/>
                          <el-date-picker v-if="item.showType==14" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]" type="date" value-format="YYYY-MM-DD"/>
                          <el-time-picker v-if="item.showType==15" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]" value-format="HH:mm:ss"/>
                          <el-date-picker v-if="item.showType==16" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"/>
                          <imageUpload v-if="item.showType==17" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"/>
                          <fileUpload v-if="item.showType==18" v-model="formData.get(formInfo.formId)[index].fieldValue[item.fieldName]"/>
                        </el-form-item>
                      </div>
                    </div>
                  </div>
                </el-form>
              </div>
              <div v-if="formInfo.showType == 2">
                <div v-for="group in formInfo.groupList">
                  <el-table :data="formData.get(formInfo.formId)" max-height="600" border style="width: 100%">
                    <template  v-for="(item, index) in group.formFieldList">
                      <el-table-column
                        v-if="item.isHidden == 'N'"
                        :key="index"
                        :prop="item.fieldName"
                        :label="item.chineseName"
                        :cell-style="{ textAlign: 'center' }"
                      >
                        <template #default="scope">
                          <el-input v-if="item.showType==1" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]"/>
                          <el-input-number v-if="item.showType==2" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]"/>
                          <el-input-number v-if="item.showType==3" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" :precision="2" v-model="scope.row.fieldValue[item.fieldName]"/>
                          <el-input v-if="item.showType==4" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]" type="textarea"/>
                          <el-select v-if="item.showType==6" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]"
                                     :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, scope.$index)"
                                     clearable filterable>
                            <el-option
                              v-for="data in item.sourceList"
                              :key="data.value"
                              :label="data.label"
                              :value="data.value"
                            ></el-option>
                          </el-select>
                          <el-select v-if="item.showType==7" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]"
                                     :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, scope.$index)"
                                     multiple clearable filterable>
                            <el-option
                              v-for="data in item.sourceList"
                              :key="data.value"
                              :label="data.label"
                              :value="data.value"
                            ></el-option>
                          </el-select>
                          <el-cascader v-if="item.showType==8" :disabled="item.isEdit=='N'" :options="item.sourceList"
                                       :placeholder="item.fieldTip"
                                       v-model="scope.row.fieldValue[item.fieldName]"
                                       :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, scope.$index)"
                                       clearable filterable/>
                          <el-cascader v-if="item.showType==9" :disabled="item.isEdit=='N'" :options="item.sourceList"
                                       :props="{ multiple: true }"
                                       :placeholder="item.fieldTip"
                                       v-model="scope.row.fieldValue[item.fieldName]"
                                       :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, scope.$index)"
                                       clearable filterable/>
                          <el-tree-select v-if="item.showType==10" :disabled="item.isEdit=='N'" v-model="scope.row.fieldValue[item.fieldName]"
                                          :placeholder="item.fieldTip"
                                          :data="item.sourceList"
                                          :render-after-expand="false"
                                          :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, scope.$index)"
                                          clearable filterable show-checkbox
                          />
                          <el-tree-select v-if="item.showType==11" :disabled="item.isEdit=='N'" v-model="scope.row.fieldValue[item.fieldName]"
                                          :placeholder="item.fieldTip"
                                          :data="item.sourceList"
                                          :render-after-expand="false"
                                          :ref="el => getTreeRef(el, item.sheetFieldId, formInfo.formId, scope.$index)"
                                          show-checkbox multiple clearable filterable
                          />
                          <el-date-picker v-if="item.showType==12" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]" type="year" value-format="YYYY" />
                          <el-date-picker v-if="item.showType==13" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]" type="month" value-format="YYYY-MM"/>
                          <el-date-picker v-if="item.showType==14" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]" type="date" value-format="YYYY-MM-DD"/>
                          <el-time-picker v-if="item.showType==15" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]" value-format="HH:mm:ss"/>
                          <el-date-picker v-if="item.showType==16" :disabled="item.isEdit=='N'" :placeholder="item.fieldTip" v-model="scope.row.fieldValue[item.fieldName]" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"/>
                          <imageUpload v-if="item.showType==17" v-model="scope.row.fieldValue[item.fieldName]"/>
                          <fileUpload v-if="item.showType==18" v-model="scope.row.fieldValue[item.fieldName]"/>
                        </template>
                      </el-table-column>
                    </template>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                      <template #default="scope">
                        <el-tooltip :content="button.showName" placement="top" v-for="button in formInfo.buttonList">
                          <el-button v-if="button.buttonCode === 'formDelete'" :type="button.buttonType" :icon="button.buttonIcon" link @click="handleChildFormDelete(formInfo.formId, formInfo.sheet, scope.$index)"></el-button>
                        </el-tooltip>
                      </template>
                    </el-table-column>
                  </el-table>
                  <span v-for="button in formInfo.buttonList">
                    <el-button class="mt-4" style="width: 100%" v-if="button.buttonCode === 'formAdd'"  @click="handleChildFormAdd(formInfo.formId)">{{ button.showName }}</el-button>
                  </span>

                </div>
              </div>
<!--            </div>-->

            <el-divider v-if="tabIndex > 1"/>

          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div class="dialog-footer">
      <span v-for="form in formInfoList">
        <el-button v-if="form.isChild === 0" v-for="item in form.buttonList"
                   :type="item.buttonType" :icon="item.buttonIcon"
                   @click="masterFormButtonClick(item)">{{ item.showName }}</el-button>
      </span>
<!--      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button >取 消</el-button>-->
    </div>

  </div>
</template>

<script setup name="PlatformForm" lang="ts">
import { onMounted } from 'vue';
import { useRoute } from 'vue-router'
import { getSheetFormInfo } from "@/api/sheet/platform/form";
import { FormCheckDto, FormDataDto, FormInfoDto, TabDto } from "@/api/sheet/platform/form/types";
import { SheetSelectVO } from "@/api/sheet/sheetSelect/types";
import { clone } from "@/utils/ruoyi";
import { SearchButtonDto } from "@/api/sheet/platform/list/types";
import { requestPost } from "@/api/sheet/platform";
import { SheetVO } from "@/api/sheet/sheet/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route=useRoute()
const loading = ref(true);
/** 默认页签 */
const activeName = ref()
/** 应用ID */
const sheetId = ref<any>("");
/** 主表单据ID */
const orderId = ref<any>("");
/** 页签信息 */
const tabList = ref<TabDto[]>([]);
/** 表单信息 */
const formInfoList = ref<FormInfoDto[]>([]);
/** 表单校验信息 */
const formCheckList = ref<FormCheckDto[]>([]);
/** 表单数据 */
const formDataList = ref<FormDataDto[]>([]);
/** 表单数据 */
const formData = ref<any>();
/** 选中数据 */
const selectList = ref<SheetSelectVO[]>([]);
/**
 * 子表删除数据
 */
const childDelList = ref<any[]>([]);


/** 存放选择框的ref */
const selectRefMap = ref(new Map());
/** 设置选择框的ref */
const getTreeRef = (el:any, value:any, formId: any, index: number) => {
  if (el) {
    if (!selectRefMap.value.has(value)){
      selectRefMap.value.set(value+formId+index, el);
    }
  }
};

/**
 * 获取表单渲染数据
 */
const getFormInfo = async()=> {
  const res = await getSheetFormInfo(sheetId.value, orderId.value);
  tabList.value = res.data.tabList;
  formInfoList.value = res.data.formInfoList;
  formCheckList.value = res.data.formCheckList;
  formDataList.value = res.data.formDataList;
  // 设置默认tab栏
  activeName.value = tabList.value[0].tabName;
  // 表单数据
  const map = new Map();
  res.data.formDataList.forEach(item => {
    let arr = new Array();
    item.fieldValue.forEach((value:any)=>{
      const dataValue = {
        fieldValue: value
      }
      arr.push(dataValue);
    })
    map.set(item.formId, arr)


  })
  formData.value = map;

  loading.value = false;
}

/** 提交表单 */
const submitForm = async(url: string) => {
  console.info("表单数据=>", formData.value);
  // 获取表单的选择字段数据
  let map = new Map();
  formInfoList.value.forEach(info => {
    info.groupList.forEach(group => {
      let selectField = group.formFieldList.filter(field => {
        if ([6,7,8,9,10,11].includes(field.showType)){
          return field
        }
      })
      map.set(info.formId, selectField);
    })
  })

  // 设置表单选择的数据
  selectList.value = [];
  map.forEach((fieldList, key) => {
    for (let i = 0; i < formData.value.get(key).length; i++) {
      fieldList.forEach((field:any) => {
        let selectValue = formData.value.get(key)[i].fieldValue[field.fieldName];
        // 普通单选或多选
        if (field.showType == 6 || field.showType == 7){
          if (selectValue){
            let selectData = selectRefMap.value.get(field.sheetFieldId+key+i).selected;
            if (Array.isArray(selectData)){
              selectData.forEach(item => {
                if (item.value){
                  saveSelectList(key, field.sheetId, field.sheetFieldId,item.value, '', item.currentLabel, item.value, i);
                }
              })
            } else {
              saveSelectList(key, field.sheetId, field.sheetFieldId,selectData.value, '', selectData.currentLabel, selectData.value, i);
            }
          }
        }
        // 级联单选或多选
        if (field.showType == 8 || field.showType == 9){
          if (selectValue){
            let selectData = selectRefMap.value.get(field.sheetFieldId+key+i).getCheckedNodes();
            selectData.forEach((item: any) => {
              if (item.children.length == 0) {
                saveSelectList(key, field.sheetId, field.sheetFieldId,item.value, item.pathValues.join(','), item.pathLabels.join(","), item.pathValues.join(','), i);
              }
            })
          }
        }
        // 树状单选或多选
        if (field.showType == 10 || field.showType == 11){
          if (selectValue){
            let selectData = selectRefMap.value.get(field.sheetFieldId+key+i).getCheckedNodes();
            selectData.forEach((item: any) => {
              saveSelectList(key, field.sheetId, field.sheetFieldId, item.value, item.path, item.label, item.value, i);
            })
          }
        }
        /*if (field.showType == 11){
          if (selectValue){
            let selectData = selectRefMap.value.get(field.sheetFieldId+key+i).getCheckedNodes();
            selectData.forEach((item: any) => {
              saveSelectList(key, field.sheetId, field.sheetFieldId, item.value, item.path, item.label, item.value, i);
            })
          }
        }*/
      })
    }
  })
  console.info(1111,  selectList.value)

  let masterFormId: string | number;
  formInfoList.value.forEach(info => {
    if (info.isChild == 0){
      masterFormId = info.formId;
    }
  })
  let masterDataList = new Array();
  let childDataList = new Array();
  formData.value.forEach((formDataValue:any, key:any) =>{
    let arr = new Array();
    formDataValue.forEach((value:any) => {
      arr.push(value.fieldValue);
    })
    let data = {
      formId: key,
      fieldValue: arr
    }
    if (key == masterFormId){
      masterDataList.push(data);
    } else {
      childDataList.push(data);
    }

  });

  const requestData = {
    masterDataList: masterDataList,
    childDataList: childDataList,
    selectDataList: selectList.value,
    sheetId: sheetId.value,
    childDelList: childDelList.value
  }
  console.info("请求参数=>", requestData)

  // let res = await postFormData(requestData);
  let res = await requestPost(url, requestData);
  orderId.value = res.data;
  await getFormInfo();
  proxy?.$modal.msgSuccess("修改成功");
}

/**
 * 设置选择数据
 * @param formId    表单ID
 * @param sheetId   应用ID
 * @param fieldId   字段ID
 * @param selectId  选择的值
 * @param path      路径
 * @param name      名称
 * @param showPath  显示路径
 * @param index     对应数据下标
 */
const saveSelectList = (formId: string|number, sheetId: string|number, fieldId: string|number, selectId: any, path: string, name: string, showPath: string, index: number) => {
  let data: SheetSelectVO = {
    orderId: '',
    formId: formId,
    sheetId: sheetId,
    fieldId: fieldId,
    selectId: selectId,
    path: path,
    name: name,
    showPath: showPath,
    index: index
  }
  selectList.value.push(data);
}

/**
 * 添加子表单数据
 * @param formId
 */
const handleChildFormAdd= (formId: String|number)=>{

  let filterList = formDataList.value.filter( item => item.formId == formId);
  if (filterList.length > 0){

    let filterData = clone(filterList[0].fieldValue[0]);
    for (let [key, value] of Object.entries(filterData)) {
      if (value){
        filterData[key] = null;
      }
    }
    let data = {
      fieldValue: filterData
    }
    formData.value.get(formId).push(data)
  }
}

/**
 * 删除子表单数据
 * @param formId  表单ID
 * @param sheet   应用详情
 * @param index   下标
 */
const handleChildFormDelete= (formId: String|number, sheet: SheetVO, index: number) => {
  let tableId = formData.value.get(formId)[index].fieldValue[sheet.tableId]
  console.info("tableId=>",  tableId)
  if (tableId != null){
    let data = {
      formId: formId,
      fieldValue: formData.value.get(formId)[index].fieldValue
    }
    childDelList.value.push(data);
  }
  formData.value.get(formId).splice(index,1)

}

/**
 * 主表单按钮点击事件
 * @param item
 */
const masterFormButtonClick= (item: SearchButtonDto) =>{
  if (item.buttonCode == "save"){
    submitForm(item.apiUrl);
  }
}

// proxy?.$tab.openPage('/platform/form/index/'+ sheetId.value, '用户管理22');

onMounted(()=>{
  console.log('query参数=>',route.query)
  sheetId.value = route.params.sheetId;
  orderId.value = route.query.orderId;

  getFormInfo();

})

</script>


